//
//  NetImage.swift
//  WxToutiao
//
//  Created by YQ05 on 2018/4/13.
//  Copyright © 2018年 yons. All rights reserved.
//

import Foundation

// url带中文的，urlString必须经过处理，加addingPercentEncoding，不然catPictureURL为nil,不带中文就不需要
// 这个是url带中文的处理方法
//        let urlString = "http://localhost:8080/AlbumImage/杀破狼.jpg"
//        let unsafeP = urlString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet(charactersIn:"`#%^{}\"[]|\\<> ").inverted)!
//        let catPictureURL = URL(string: unsafeP)!


extension UIImageView {
    func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleToFill) {
        contentMode = mode
        
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            // The download has finished.
            if let e = error {
                print("Error downloading cat picture: \(e)")
            } else {
                // No errors found.
                // It would be weird if we didn't have a response, so check for that too.
                if let res = response as? HTTPURLResponse {
                    //print("Downloaded cat picture with response code \(res.statusCode)")
                    if let imageData = data {
                        // Finally convert that Data into an image and do what you wish with it.
                        let image = UIImage(data: imageData)
                        // Do something with your image.
                        DispatchQueue.main.async() { () -> Void in
                            self.image = image
                        }
                        
                    } else {
                        print("Couldn't get image: Image is nil")
                    }
                } else {
                    print("Couldn't get response code for some reason")
                }
            }
            
            }.resume()
        
    }
    func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        downloadedFrom(url: url, contentMode: mode)
    }
}

////创建URL对象
//let url = URL(string: safeImg)!
////创建请求对象
//let request = URLRequest(url: url)
//
//let session = URLSession.shared
//let dataTask = session.dataTask(with: request, completionHandler: {
//    (data, response, error) -> Void in
//    if error != nil{
//        print(error.debugDescription)
//    }else{
//        //将图片数据赋予UIImage
//        let img = UIImage(data:data!)
//        DispatchQueue.main.async { // Correct
//            cell.NewsimgView.image = img
//        }
//    }
//
//}) as URLSessionTask
//
////使用resume方法启动任务
//dataTask.resume()

